<template>
	<view class="wrap">

		<!-- 内容区域 -->
		<view class="content">
			<!-- 表单内容 -->
			<view class="form-container">
				<u-form :model="form" :rules="rules" ref="uForm" label-width="120" label-position="top">
					<u-form-item label="作业名称" prop="jobName">
						<u-input :border="true" v-model="form.jobName"></u-input>
					</u-form-item>
					<u-form-item label="作业日期" prop="jobTime">
						<u-input :border="true" v-model="form.jobTime" :disabled="true" placeholder="请选择日期"
							:clearable="true" @click="showCalendar = true"></u-input>
					</u-form-item>
					<u-form-item label="完成条件" prop="jobCompletionConditions">
						<u-radio-group v-model="form.jobCompletionConditions">
							<u-radio v-for="option in completionOptions" :key="option.value"
								:name="option.value">{{ option.label }}</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="作业班级" prop="classManage">
						<u-checkbox-group :wrap="true">
							<u-checkbox v-for="item in classOptions" :key="item.id" :name="item.id"
								v-model="item.checked">{{ item.classManagementName }}</u-checkbox>
						</u-checkbox-group>
					</u-form-item>
					<!-- 选择书籍 -->
					<u-form-item label="选择书籍" prop="bookId" required>
						<view class="book-selection">
							<u-button type="primary" size="medium" shape="circle" @click="selectBook">
								{{ selectedBooks.length > 0 ? '已选择书籍' : '选择书籍' }}
							</u-button>
							<view class="selected-books" v-if="selectedBooks.length > 0">
								<view class="book-item" v-for="(book, index) in selectedBooks" :key="book.id">
									<image class="book-cover" :src="getBookCoverUrl(book)" mode="aspectFit"></image>
									<view class="book-info">
										<text class="book-name">{{ book.bookName }}</text>
										<text class="book-author" v-if="book.author">{{ book.author }}</text>
									</view>
									<view class="remove-book" @click="removeBook(index)">
										<u-icon name="close-circle" size="20" color="#ff4757"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</u-form-item>
				</u-form>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="footer-bar">
			<u-button type="primary" shape="circle" @click="createHomework" :loading="loading" :disabled="loading">
				{{ loading ? '创建中...' : '创建作业' }}
			</u-button>
		</view>

		<u-picker v-model="showCalendar" :default-time="form.jobTime" mode="time" @confirm="dateChange"></u-picker>

	</view>
</template>

<script>
	import {
		createBookSchoolAssignment
	} from '@/api/bookSchoolAssignment'
	import {
		formatDate
	} from "@/utils/util";
	import {
		getBookClassManagementList
	} from '@/api/bookSchoolAssignment'
	export default {
		data() {
			return {
				completionOptions: [{
						value: '1',
						label: '完成配音'
					},
					{
						value: '2',
						label: '完成阅读'
					}
				],
				classOptions: [],
				statusBarHeight: 0,
				loading: false,

				form: {
					bookId: '',
					jobName: '',
					jobTime: '',
					jobCompletionConditions: '',
					classManage: []
				},
				selectedBooks: [],
				rules: {
					bookId: [{
						required: true,
						message: '请选择书籍',
						trigger: ['blur', 'change']
					}]
				},
				showCalendar: false,
				date: ''
			}
		},

		onLoad(options) {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;

			if(this.checkLoginStatus()){
				this.loadClassData();
			}
		},
		computed: {
			selectedClassIds() {
				return this.classOptions
					.filter(item => item.checked)
					.map(item => item.id);
			}
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = this.$store.getters.token;
				if (!token) {
					// 没有token，跳转到登录页面
					uni.showModal({
						title: '提示',
						content: '请先登录后再使用此功能',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/index'
								});
							}
						}
					});
					return false;
				}
				return true;
			},
			/**
			 * 返回上一页
			 */
			goBack() {
				uni.navigateBack();
			},

			dateChange(e) {
				this.form.jobTime = `${e.year}-${e.month}-${e.day}`
				console.log(e)
			},
			/**
			 * 加载班级数据
			 */
			async loadClassData() {
				try {


					const resp = await getBookClassManagementList();
					if (resp.code === 0) {
						this.classOptions = resp.data;
					}

				} catch (error) {
					console.error('加载班级数据失败:', error);
					uni.showToast({
						title: '加载班级数据失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 选择书籍
			 */
			selectBook() {
				uni.navigateTo({
					url: '/pages/class/select-homework-book',
					events: {
						// 监听选择书籍事件
						selectBook: (data) => {
							this.addSelectedBook(data.book);
						}
					}
				});
			},

			/**
			 * 添加选中的书籍
			 */
			addSelectedBook(book) {
				// 只选择一本书籍
				this.selectedBooks = [book];
				this.form.bookId = book.id;
				uni.showToast({
					title: '书籍选择成功',
					icon: 'success'
				});
			},

			/**
			 * 移除选中的书籍
			 */
			removeBook(index) {
				this.selectedBooks.splice(index, 1);
				this.form.bookId = '';
			},

			/**
			 * 获取书籍封面URL
			 */
			getBookCoverUrl(book) {
				if (book && book.image) {
					return book.image;
				}
				return '/static/empty.png';
			},



			/**
			 * 表单验证
			 */
			validateForm() {
				return new Promise((resolve) => {
					this.$refs.uForm.validate((valid) => {
						if (valid) {
							resolve(true);
						} else {
							uni.showToast({
								title: '请完善表单信息',
								icon: 'none'
							});
							resolve(false);
						}
					});
				});
			},

			/**
			 * 创建作业
			 */
			async createHomework() {
				const isValid = await this.validateForm();
				if (!isValid) {
					return;
				}

				this.loading = true;
				uni.showLoading({
					title: '创建中...'
				});

				try {
					// 调用创建作业接口
					const result = await createBookSchoolAssignment({
						bookId: this.form.bookId,
						classIds: this.selectedClassIds,
						jobName: this.form.jobName,
						jobTime: this.form.jobTime,
						jobCompletionConditions: this.form.jobCompletionConditions,
					});

					uni.hideLoading();

					// 判断接口调用是否成功
					if (result.code === 0) {
						uni.showToast({
							title: '创建作业成功',
							icon: 'success'
						});

						// 延迟返回上一页并刷新数据
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
							// 触发页面刷新事件
							uni.$emit('refreshHomeworkList');
						}, 1500);
					} else {
						uni.showToast({
							title: result.msg || '创建作业失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('创建作业失败:', error);
					uni.showToast({
						title: '创建作业失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 返回上一页
			 */
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style>
	.wrap {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.status-bar {
		width: 100%;
		background-color: #007AFF;
	}

	.nav-bar {
		height: 88rpx;
		background-color: #007AFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
	}

	.nav-back {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		font-size: 40rpx;
		color: #fff;
		font-weight: bold;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #fff;
	}

	.nav-placeholder {
		width: 60rpx;
	}

	.content {
		background-color: #f5f5f5;
		min-height: calc(100vh - 88rpx);
		padding: 20rpx;
	}

	.form-container {
		background-color: #fff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.book-selection {
		width: 100%;
	}

	.selected-books {
		margin-top: 20rpx;
	}

	.book-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
		border: 1rpx solid #e9ecef;
		margin-bottom: 16rpx;
	}

	.book-item:last-child {
		margin-bottom: 0;
	}

	.book-cover {
		width: 80rpx;
		height: 100rpx;
		border-radius: 8rpx;
		margin-right: 20rpx;
		background-color: #e5e5e5;
	}

	.book-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.book-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	.book-author {
		font-size: 24rpx;
		color: #666;
	}

	.remove-book {
		padding: 10rpx;
	}

	.footer-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 32rpx;
		border-top: 1rpx solid #f0f0f0;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}
</style>